const express = require('express');
const router = express.Router();
const { v4: uuidv4 } = require('uuid');
const db = require('../config/db');
const { checkEventConflict } = require('../utils/eventConflict');

// 获取日程列表
router.get('/', async (req, res) => {
  try {
    // 获取查询参数
    const { classId, type, startDate, endDate } = req.query;

    let query = `
      SELECT e.*, c.name as course_name, u.nickname as creator_name 
      FROM events e
      LEFT JOIN courses c ON e.course_id = c.id
      LEFT JOIN users u ON e.user_id = u.id
      WHERE (e.user_id = ? OR e.event_type = 'public')
    `;
    let params = [req.user.id];

    // 添加筛选条件
    if (classId) {
      query += ' AND c.class_id = ?';
      params.push(classId);
    }
    if (type) {
      query += ' AND e.event_type = ?';
      params.push(type);
    }
    if (startDate) {
      query += ' AND e.start_time >= ?';
      params.push(startDate);
    }
    if (endDate) {
      query += ' AND e.end_time <= ?';
      params.push(endDate);
    }

    query += ' ORDER BY e.start_time ASC';

    const [events] = await db.execute(query, params);
    res.json(events);
  } catch (error) {
    res.status(500).json({ error: '获取日程列表失败' });
  }
});

// 添加日程
router.post('/', async (req, res) => {
  try {
    const { 
      classId,
      courseId,
      title, 
      description, 
      startTime, 
      endTime, 
      eventType 
    } = req.body;

    // 如果是公共日程，检查是否为老师
    if (eventType === 'public') {
      const [members] = await db.execute(
        'SELECT role FROM class_members WHERE class_id = ? AND user_id = ?',
        [classId, req.user.id]
      );

      if (!members.length || members[0].role !== 'teacher') {
        return res.status(403).json({ error: '只有老师可以创建公共日程' });
      }
    }

    // 检查日程冲突
    const { hasConflict, conflicts } = await checkEventConflict(
      req.user.id,
      startTime,
      endTime
    );

    if (hasConflict) {
      return res.status(400).json({
        error: '日程时间冲突',
        conflicts: conflicts.map(event => ({
          title: event.title,
          startTime: event.start_time,
          endTime: event.end_time,
          type: event.event_type
        }))
      });
    }

    // 创建日程
    const id = uuidv4();
    await db.execute(
      `INSERT INTO events (
        id, user_id, course_id, title, description, 
        start_time, end_time, event_type
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      [id, req.user.id, courseId, title, description, startTime, endTime, eventType]
    );

    res.json({ id });
  } catch (error) {
    res.status(500).json({ error: '添加日程失败' });
  }
});

// 修改日程
router.put('/:id', async (req, res) => {
  try {
    const { 
      title, 
      description, 
      startTime, 
      endTime 
    } = req.body;

    // 检查日程是否存在且是否有权限修改
    const [events] = await db.execute(
      'SELECT * FROM events WHERE id = ?',
      [req.params.id]
    );

    if (events.length === 0) {
      return res.status(404).json({ error: '日程不存在' });
    }

    const event = events[0];

    // 只能修改自己创建的日程
    if (event.user_id !== req.user.id) {
      return res.status(403).json({ error: '无权修改此日程' });
    }

    // 检查日程冲突
    const { hasConflict, conflicts } = await checkEventConflict(
      req.user.id,
      startTime,
      endTime,
      req.params.id
    );

    if (hasConflict) {
      return res.status(400).json({
        error: '日程时间冲突',
        conflicts: conflicts.map(event => ({
          title: event.title,
          startTime: event.start_time,
          endTime: event.end_time,
          type: event.event_type
        }))
      });
    }

    // 更新日程
    await db.execute(
      `UPDATE events 
       SET title = ?, description = ?, start_time = ?, end_time = ? 
       WHERE id = ?`,
      [title, description, startTime, endTime, req.params.id]
    );

    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: '修改日程失败' });
  }
});

// 删除日程
router.delete('/:id', async (req, res) => {
  try {
    // 检查日程是否存在且是否有权限删除
    const [events] = await db.execute(
      'SELECT * FROM events WHERE id = ?',
      [req.params.id]
    );

    if (events.length === 0) {
      return res.status(404).json({ error: '日程不存在' });
    }

    const event = events[0];

    // 只能删除自己创建的日程
    if (event.user_id !== req.user.id) {
      return res.status(403).json({ error: '无权删除此日程' });
    }

    // 删除日程
    await db.execute(
      'DELETE FROM events WHERE id = ?',
      [req.params.id]
    );

    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: '删除日程失败' });
  }
});

// 更新日程状态
router.patch('/:id/status', async (req, res) => {
  try {
    const { status } = req.body;

    // 检查日程是否存在且是否有权限更新
    const [events] = await db.execute(
      'SELECT * FROM events WHERE id = ?',
      [req.params.id]
    );

    if (events.length === 0) {
      return res.status(404).json({ error: '日程不存在' });
    }

    const event = events[0];

    // 只能更新自己的日程状态
    if (event.user_id !== req.user.id) {
      return res.status(403).json({ error: '无权更新此日程状态' });
    }

    // 更新状态
    await db.execute(
      'UPDATE events SET status = ? WHERE id = ?',
      [status, req.params.id]
    );

    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: '更新日程状态失败' });
  }
});

// 设置/取消星标
router.patch('/:id/star', async (req, res) => {
  try {
    const { isStarred } = req.body;

    // 检查日程是否存在
    const [events] = await db.execute(
      'SELECT * FROM events WHERE id = ?',
      [req.params.id]
    );

    if (events.length === 0) {
      return res.status(404).json({ error: '日程不存在' });
    }

    // 更新星标状态
    await db.execute(
      'UPDATE events SET is_starred = ? WHERE id = ? AND user_id = ?',
      [isStarred, req.params.id, req.user.id]
    );

    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: '更新星标状态失败' });
  }
});

module.exports = router;